package com.sbox;

import com.sbox.R;
import com.sbox.model.SBoxConfig;
import com.sbox.model.SBoxConst;
import com.sbox.util.Utils;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {
	private TitleBar mTitleBar = null;
	private EditText mEditPassword = null;
	private Button mBtnLogin = null;
	private TextView mEditBadPassword = null;
	
	
	private View.OnClickListener mBtnLoginListener = new View.OnClickListener() {		
		@Override
		public void onClick(View v) {
			String password = mEditPassword.getText().toString();
			if( password == null || password.length()== 0 )
				return;
			
			Utils.closeInputMethod(LoginActivity.this, v);
			if( VerifyPassword(password) )
			{
				mEditBadPassword.setVisibility(View.GONE);				
				LoginActivity.this.setResult(SBoxConst.REQUEST_LOGIN_OK);
				
				//hide the input method:
				Utils.closeInputMethod(LoginActivity.this, v);
				
				LoginActivity.this.finish();
			}
			else
			{
				mEditBadPassword.setVisibility(View.VISIBLE);
				mEditPassword.setText("");
			}
		}
	};
	
	
	@Override
	public void onCreate(Bundle savedBundle)
	{
		super.onCreate(savedBundle);
		setContentView(R.layout.login_view);
		
		mTitleBar = (TitleBar)findViewById(R.id.login_title);
		mTitleBar.getButton1().setVisibility(View.INVISIBLE);
		mTitleBar.getButton2().setVisibility(View.INVISIBLE);
		
		mEditPassword = (EditText)findViewById(R.id.edit_password);		
		mBtnLogin = (Button)findViewById(R.id.btn_login);
		mBtnLogin.setOnClickListener(mBtnLoginListener);	
		mEditBadPassword = (TextView)findViewById(R.id.login_bad_password);
	}
	
	
	private boolean VerifyPassword(String password)
	{		
		SBoxConfig config = SBoxConfig.getInstance(this);
		String passHash = Utils.enctypt(this, password);
		
		if( config == null )
			return false;
		
		if( config.mPasswordHash.equals(passHash))
			return true;
		
		return false;
	}	
}
